package com.mgface.zookeeper.curator.function;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;

public class 分布式计数器 {

	public static void main(String[] args) throws Exception {
		String path = "/curator-atomic";
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString("localhost:2181")
				.retryPolicy(new ExponentialBackoffRetry(1_000, 3)).build();
		client.start();
		client.delete().guaranteed().forPath(path);
		DistributedAtomicInteger dai = new DistributedAtomicInteger(client, path, new RetryNTimes(3, 1_000));
		AtomicValue<Integer> av = dai.add(8);
		System.out.println(av.succeeded());
		System.out.println(av.postValue());
		AtomicValue<Integer> av2 = dai.add(8);
		System.out.println(av2.succeeded());
		AtomicValue<Integer> av3 = dai.get();
		System.out.println(av3.postValue());
		System.out.println(new String(client.getData().forPath(path),StandardCharsets.UTF_8));
	}

}
